package com.eystar.pdc.directive;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.eystar.pdc.model.DicItem;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * <pre>
 * 获取字典code的值，类似for循环
 * #dic_for("code")
 * 	#(item_code) : #(item_value)
 * #end
 * 
 * 获取字典code的值，类似for循环。
 * #dic_for("code","-1","0")
 * 	#(item_code) : #(item_value)
 * #end
 * </pre>
 * @author Administrator
 *
 */
public class DicForDirective extends Directive {
	
	public void setExprList(ExprList exprList) {
		int len = exprList.length();
		if (len < 1) {
			throw new ParseException("指令#dic_for最少有一个参数", location);
		}
		super.setExprList(exprList);
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		String code = (String) exprList.getFirstExpr().eval(scope);
		Map<String, String> items = DicItem.dao.findDicItems(code);
		List<String> escapes = new ArrayList<String>();
		// 循环排除项
		Expr[] exprs = exprList.getExprArray();
		for (int i = 0 ; i < exprs.length ; i++) {
			if (i == 0) {
				continue;
			}
			String escape = (String) exprs[i].eval(scope);
			escapes.add(escape);
		}
		for (String key : items.keySet()) {
			if (escapes.contains(key)) {
				continue;
			}
			scope.set("item_code", key);
			scope.set("item_value", items.get(key));
			stat.exec(env, scope, writer);
		}
	}

	/**
	 * 当只有一个参数的时候，必须要有
	 */
	@Override
	public boolean hasEnd() {
		return true;
	}
}
